/**
 *
 * 编辑器地址 https://github.com/margox/braft-editor
 */

import React, {Component} from 'react';
import styles from './index.less';
import CSSModules from 'react-css-modules';
import {withRouter} from 'react-router-dom';
import {List} from 'antd';
import {Link} from 'react-router-dom';

import PageHeader from 'ant-design-pro/lib/PageHeader';
import {openPanel} from '@bizfe/biz-rc-panel';
import {connect} from 'react-redux';
import {Button, Icon, Card, message, Col, Row, Form, Input, Modal} from 'antd';
const ButtonGroup = Button.Group,
  FormItem = Form.Item,
  confirm = Modal.confirm;

import {UPLOAD_URL, ARTICLE_URL, USER_ARTICLE_URL} from 'constant/url';
import myaxios, {get, put, post, deleteAxios} from 'common/fetch';

// 引入编辑器以及编辑器样式
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/braft.css';

import Classfication from './classfication';
import Poll from './Poll';

class PostTitle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowInput: false,
      value: '',
    };
  }
  componentDidMount() {
    this.setState({
      value: this.props.value,
    });
  }
  handleClick = () => {
    this.setState({
      isShowInput: true,
    });
  };
  handleEnter = () => {
    const {onEnter} = this.props;
    const {value} = this.state;
    this.setState({
      isShowInput: false,
    });
    onEnter && onEnter(value);
  };
  handleBlur = () => {
    const {onEnter} = this.props;
    const {value} = this.state;
    this.setState({
      isShowInput: false,
    });
    //onEnter && onEnter(value);
  };
  handleChange = event => {
    this.setState({
      value: event.target.value,
    });
  };
  render() {
    const {title} = this.props;
    const {isShowInput, value} = this.state;
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 20},
      },
    };
    return (
      <FormItem>
        {isShowInput ? (
          <Input
            autoFocus
            placeholder={title}
            defaultValue={title}
            onPressEnter={this.handleEnter}
            onBlur={this.handleBlur}
            onChange={this.handleChange}
          />
        ) : (
          <div
            style={{fontSize: 20, fontWeight: 500}}
            onClick={this.handleClick}>
            {title}
          </div>
        )}
      </FormItem>
    );
  }
}

class ArticleList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      html: '',
      postDetail: {
        title: '缺省标题',
      },
    };
  }

  componentDidMount() {
    const {match} = this.props;
    let postId = match.params.articleId;
    if (postId) {
      get(`/nnc/post/${postId}`).then(res => {
        let postDetail = res && res[0];
        this.setState({
          postDetail,
        });
      });
    }
  }
  getArticleDetail() {
    const {match} = this.props;
    let postId = match.params.articleId;
    if (postId) {
      get(`/nnc/post/${postId}`).then(res => {
        let postDetail = res && res[0];
        this.setState({
          postDetail,
        });
      });
    }
  }
  handleSave = () => {
    const {postDetail} = this.state,
      {match, user} = this.props;

    if (user.role == 0) {
      //普通用户发帖
      confirm({
        title: '确定提交您的文章？',
        content: '您可以在手机端【众车轮】板块查看您发表成功的文章',
        onOk() {
          post(`${USER_ARTICLE_URL}`, {
            content: postDetail.content,
            title: postDetail.title,
          }).then(res => {
            message.success('保存成功');
            setTimeout(function() {
              window.location.reload();
            }, 1000);
          });
        },
        onCancel() {},
      });
    } else {
      let articleId = match.params.articleId;
      if (!articleId) {
        //新建文章
        post(`${ARTICLE_URL}`, {
          content: postDetail.content,
          title: postDetail.title,
          categoryId: postDetail.categoryId,
          carIds: postDetail.carIds,
          channel: postDetail.channel,
          authorId: postDetail.authorId,
          videoInfo: postDetail.videoInfo,
        }).then(res => {
          message.success('保存成功');
          this.props.history.push('/article');
        });
      } else {
        put(`${ARTICLE_URL}/${articleId}`, {
          content: postDetail.content,
          title: postDetail.title,
          categoryId: postDetail.categoryId,
          carIds: postDetail.carIds,
          channel: postDetail.channel,
          authorId: postDetail.authorId,
          videoInfo: postDetail.videoInfo,
        }).then(res => {
          message.success('保存成功');
          this.props.history.push('/article');
        });
      }
    }
  };
  updateTitle(title) {
    this.setState({
      postDetail: {...this.state.postDetail, title},
    });
  }
  updateState = obj => {
    const postDetail = {...this.state.postDetail, ...obj};

    this.setState({
      postDetail,
    });
  };
  hidePanel = () => {
    this.panelObj.close();
  };
  addPoll() {
    const {match} = this.props;
    let currentIndex = 800;
    const config = {
      customClass: styles['.biz-panel'],
      marginLeft: 200,
      top: '0',
      theme: '',
      leftCloseAble: true,
      // titleAble: true,
      title: '插入投票',
      content: (
        <Poll
          reloadPostDetail={this.getArticleDetail.bind(this)}
          postId={match.params.articleId}
          hidePanel={this.hidePanel}
        />
      ),
      buttonsAble: false,
      buttons: [
        {
          value: '确定',
          isSubmit: true,
        },
        {
          value: '取消',
        },
      ],
      onBeforeClose: function() {
        //me.getMsgList(me.getQuery());
        return true;
      },
      onCancelFunc: function() {
        return true;
      },
      submitFunc: function(closeFunc) {
        closeFunc();
      },
      zIndex: currentIndex,
    };

    this.panelObj = openPanel(config, document.body);
  }
  setClassification() {
    let currentIndex = 800;
    const config = {
      customClass: styles['.biz-panel'],
      marginLeft: 200,
      top: '0',
      theme: '',
      leftCloseAble: true,
      // titleAble: true,
      title: '设置分类',
      content: (
        <Classfication
          postDetail={this.state.postDetail}
          updateState={this.updateState}
          hidePanel={this.hidePanel}
        />
      ),
      buttonsAble: false,
      buttons: [
        {
          value: '确定',
          isSubmit: true,
        },
        {
          value: '取消',
        },
      ],
      onBeforeClose: function() {
        //me.getMsgList(me.getQuery());
        return true;
      },
      onCancelFunc: function() {
        return true;
      },
      submitFunc: function(closeFunc) {
        closeFunc();
      },
      zIndex: currentIndex,
    };

    this.panelObj = openPanel(config, document.body);
  }
  render() {
    const {postDetail} = this.state;
    debugger;
    const {match, user} = this.props;
    let postId = match.params.articleId,
      type = postId ? 'edit' : 'add';
    const editorProps = {
      height: 500,
      contentFormat: 'html',
      initialContent: postDetail.content,
      onChange: this.handleChange,
      onHTMLChange: this.handleHTMLChange,
      media: {
        uploadFn: this.handleUploadImg,
      },
    };
    return (
      <div className={styles['home-wrap']}>
        <PageHeader
          title={
            <PostTitle
              title={postDetail.title}
              onEnter={value => {
                if (value != postDetail.title) {
                  this.updateTitle(value);
                }
              }}
            />
          }
          action={
            <ButtonGroup>
              {/*
              <Button>
                <Icon type="profile" />插入投票
              </Button>
              */}
              {user.role == 1 ? (
                <Button onClick={this.setClassification.bind(this)}>
                  <Icon type="setting" />设置
                </Button>
              ) : null}
              {user.role == 1 && postDetail.postId? (
                !postDetail.pollId ? (
                  <Button onClick={this.addPoll.bind(this)}>
                    <Icon type="pie-chart" />插入投票
                  </Button>
                ) : (
                  <Button>
                    <Icon type="pie-chart" />已插投票
                  </Button>
                )
              ) : null}
              <Button onClick={this.handleSave} type="primary">
                <Icon type="save" />保存文章
              </Button>
            </ButtonGroup>
          }
          breadcrumbList={
            user.role == 1
              ? [
                  {
                    title: '文章列表',
                    href: '/article',
                  },
                  {
                    title: '编辑文章',
                  },
                ]
              : [
                  {
                    title: '创建文章',
                  },
                ]
          }
          linkElement={Link}
          className={styles.pageHeader}
        />
        <div className={`${styles.content} ${styles['home-container']}`}>
          <Card style={{margin: 24}} bordered={false}>
            <Row>
              {/* <Col span={12}>
                                <div dangerouslySetInnerHTML={{ __html: html }} />
                            </Col> */}
              {/* 暂时不加入即时预览，因为编辑器是实时显示结果的 */}
              <Col span={24}>
                <Card bordered={true}>
                  <BraftEditor {...editorProps} />
                </Card>
              </Col>
            </Row>
          </Card>
        </div>
      </div>
    );
  }

  handleHTMLChange = content => {
    this.setState({
      postDetail: {
        ...this.state.postDetail,
        content,
      },
    });
  };

  handleUploadImg = param => {
    console.log(param);
    const serverURL = UPLOAD_URL;
    const xhr = new XMLHttpRequest();
    const fd = new FormData();

    // libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
    // console.log(param.libraryId);

    const successFn = response => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      let _rel = JSON.parse(xhr.response);
      if (_rel.code == 0) {
        param.success({
          url: _rel.data.url,
        });
      } else {
        param.error({
          msg: _rel.msgs,
        });
      }
    };

    const progressFn = event => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100);
    };

    const errorFn = response => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);

    fd.append('file', param.file);
    xhr.open('POST', serverURL, true);
    xhr.send(fd);
  };
}

const mapStateToProps = state => {
  return {user: state.user};
};
export default withRouter(connect(mapStateToProps)(ArticleList));
